<!-- 文件上传和下载 -->
<template>
  <div class="upload-page">
    <!-- 上传区 -->
    <el-col>
        <el-row class="input_file_title">上传文件</el-row>
          <el-row class="input_file_box">
            <input ref="fileInput" type="file" style="display: none;" @change="handleFileChange"/>
            <div class="upload-box" @click="openFileDialog()">
              <i class="el-icon-upload" style="font-size:24px; color:#409EFF;"></i>
              <p>点击或拖拽文件到此处上传</p>
            </div>
        </el-row>
        <el-row class="input_file_box">
          <el-col :span="4"><el-text>原文件名</el-text></el-col>
          <el-col :span="16"><el-input v-model="selectedFileName" readonly="" placeholder="未选择文件"></el-input></el-col>
        </el-row>
        <el-row class="input_filename">
          <el-col :span="4"><el-text>输入保存后的文件名称</el-text></el-col>
          <el-col :span="16"><el-input v-model="name" placeholder="输入文件名"></el-input></el-col>
        </el-row>
        <el-row class="input_description">
          <el-col :span="4"><el-text>描述信息</el-text></el-col>
          <el-col :span="16"><el-input v-model="description" class="des_box" placeholder="输入文件描述"></el-input></el-col>
        </el-row>
        <el-row class="input_chapter">
          <el-col :span="4"><el-text>所属章节</el-text></el-col>
          <el-col :span="16">
            <el-select v-model="selectedChapterId" placeholder="请选择章节">
              <el-option
                v-for="opt in chapterOptions"
                :key="opt.id"
                :label="opt.titleFormatted"
                :value="opt.id"
              />
            </el-select>
          </el-col>
        </el-row>
      </el-col>
    <div>
        <el-row class="filename">
          <el-col><el-button @click="submitUpload()">确认上传</el-button></el-col>
        </el-row>
    </div>

    <el-divider></el-divider>

    <!-- 删除文件控制区 -->
    <div class="delete-control" v-if="showDeletePanel">
      <el-input
        type="textarea"
        :rows="3"
        readonly
        v-model="deleteNames"
        placeholder="待删除文件名"
      />
      <el-button type="danger" @click="confirmDelete">确认删除</el-button>
      <el-button @click="cancelDelete">取消</el-button>
    </div>
    <el-button v-else type="warning" @click="toggleDeletePanel">删除文件</el-button>
    
    <!-- 列表展示区 -->
    <el-table
      v-if="records.length"
      :data="records"
      border
      stripe
      style="width: 100%; margin: 16px;"
      @selection-change="handleSelectionChange"
      >
        <el-table-column
         type="selection"
          width="55"
          v-if="showDeletePanel"
        />
      <el-table-column prop="createTime" label="创建时间" />
      <el-table-column prop="createBy" label="创建人" width="100" />
      <el-table-column prop="name" label="文件名" />
      <el-table-column prop="path" label="路径" />
      <el-table-column prop="course" label="课程 ID" width="100" />
      <el-table-column prop="type" label="文件类型" width="140" />
    </el-table>
    <div v-else class="no-data">暂无数据，请先点击“查询”</div>

    <!-- 分页查询区 -->
    <div class="query-box">
      <el-form :inline="true" class="query-form">
        <el-form-item label="页码">
          <el-input-number v-model="pageNum" :min="1" />
        </el-form-item>
        <el-form-item label="每页条数">
          <el-input-number v-model="pageSize" :min="1" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="fetchPage">查询</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import axios from 'axios'
import { useCookies } from 'vue3-cookies'

const { cookies } = useCookies()

const fileInput = ref(null)
const selectedFile = ref(null)
const selectedFileName = ref("")
const name = ref('')
const description = ref('')

// 章节相关
const course = ref(null)
const chapterOptions = ref([])
const selectedChapterId = ref(null)
const rawChapters = ref([])

// 获取课程 ID
onMounted(async () => {
  const stored = cookies.get('selectedCourse')
  if (stored) {
    course.value = Number(stored.id)
    try {
      const res = await axios.get('/api/chapter/courseid', { params: { courseID: course.value } })
      if (res.data?.code === 200){
        rawChapters.value = res.data.data || []
        buildChapterOptions()
      }
    } catch {
      console.error('获取章节列表失败', e)
    }
    fetchPage()
  }
})

// 构建平铺、排序、缩进的章节选项
function buildChapterOptions() {
  chapterOptions.value = []
  const traverse = (nodes, prefix = '') => {
    nodes
      .sort((a, b) => a.sortOrder - b.sortOrder)
      .forEach(node => {
        chapterOptions.value.push({
          id: node.id,
          titleFormatted: prefix + node.title,
          parentID: node.parentID
        })
        if (node.children && node.children.length > 0) {
          traverse(node.children, prefix + '  ') // 缩进两个空格
        }
      })
  }
  traverse(rawChapters.value)
}

/** 打开本地文件选择对话框 */
function openFileDialog() {
  fileInput.value.click()
}

/** 选择文件后缓存，不立即上传 */
function handleFileChange(event) {
  const files = event.target.files
  if (!files || files.length === 0) return
  selectedFile.value = files[0]
  selectedFileName.value = selectedFile.value.name
  // 重置输入框，以便下次选择同一文件也能触发 change
  event.target.value = ''
}

/** 点击按钮后，统一上传所有数据 */
async function submitUpload() {
  if (!selectedFile.value) {
    alert('请先选择文件')
    return
  }
  // 校验章节支持性：必须有 parentID
  const opt = chapterOptions.value.find(o => o.id === selectedChapterId.value)
  if (!opt || opt.parentID == null) {
    alert('父章节不支持添加文件')
    return
  }
  const formData = new FormData()
  formData.append('name', name.value)
  formData.append('course', course.value)
  formData.append('description', description.value)
  formData.append('multipartFile', selectedFile.value)
  formData.append('chapter', selectedChapterId.value)

  try {
    await axios.post('/api/course/file/add', formData, {
      headers: { 'Content-Type': 'multipart/form-data' }
    })
    alert('上传成功')
    // 上传成功后可清空字段
    name.value = ''
    description.value = ''
    selectedFile.value = null
    selectedChapterId.value = null
    fetchPage()
  } catch (err) {
    console.error('上传失败：', err)
    alert('上传失败，请重试')
  }
}



// 分页查询
const pageNum = ref(1)
const pageSize = ref(10)
const records = ref([])

// 删除文件控制
const showDeletePanel = ref(false)
const deleteIds = ref([])
const deleteNames = ref('')

async function fetchPage() {
  try {
    let courseid = course.value.toString()
    const res = await axios.get('/api/course/file/page', {
        params:{
            pageNum: pageNum.value,
            pageSize: pageSize.value,
            course: courseid
        }
    })
    console.log(res)
    const recs = res.data.data.records || []

    // 2. 并发调用接口获取每条记录的创建人名称
    const withNames = await Promise.all(
      recs.map(async r => {
        let name = ''
        try {
          const userResp = await axios.get(`/api/customer/user/id?id=${r.createBy}`)
          if (userResp.data?.code === 200) {
            name = userResp.data.data.username
            console.log(name)
          }
        } catch (e) {
          console.warn('获取用户信息失败', e)
        }
        // 在原 record 上挂载 creatorName
        return {
          ...r,
          createBy: name
        }
      })
    )
    // 3. 更新表格数据
    records.value = withNames
  } catch(e) {
    console.log(e)
    alert('网络错误，查询失败')
  }
}

// 删除面板切换
function toggleDeletePanel() {
  showDeletePanel.value = true
}

// 取消删除
function cancelDelete() {
  showDeletePanel.value = false
  deleteIds.value = []
  deleteNames.value = ''
}

// 选择变化
function handleSelectionChange(selectedRows) {
  deleteIds.value = selectedRows.map(r => r.id)
  deleteNames.value = selectedRows.map(r => r.name || r.path || r.id).join(', ')
}

// 确认删除
async function confirmDelete() {
  for (const id of deleteIds.value) {
    console.log("delete id: "+id)
    await axios.delete('/api/course/file/delete/id', { params: { id : id } })
  }
  cancelDelete()
  fetchPage()
}

</script>


<style scoped>
.upload-page {
  padding: 24px;
  background: hsla(216, 33%, 97%, 0.6);
  min-height: 100vh;
}

/* 上传区 */
.upload-box {
  width: 80%;
  height: 180px;
  border: 2px dashed #d3dce6;
  border-radius: 6px;
  background: #fff;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  transition: border-color .3s;
  margin-bottom: 24px;
}
.upload-box:hover {
  border-color: #409EFF;
}
.upload-box p {
  margin: 8px 0 0;
  color: #909399;
  font-size: 14px;
}
.fixed-row {
  height: 100px;         /* 行容器高度为视口高度的 40% */
  display: flex;        /* flex 布局 */
  align-items: center;  /* 垂直居中内容 */
}
.filename{
    height: 80px;
    justify-content: center;
    align-items: center;  /* 垂直居中内容 */
}
.input_file_title{
    justify-content: center;
    align-items: center;  /* 垂直居中内容 */
    height: 60px;
}
.input_file_box{
    justify-content: center;
    align-items: center;  /* 垂直居中内容 */
}
.input_description{
    justify-content: center;
    align-items: center;  /* 垂直居中内容 */
    height: 160px;
}
.input_filename{
    justify-content: center;
    align-items: center;  /* 垂直居中内容 */
    margin-top: 30px;
}

.input_chapter {
  justify-content: center;
  align-items: center;
  margin-top: 16px;
}

.des_box{
    height: 100px;
}

/* 查询区 */
.query-box {
  background: #fff;
  padding: 16px;
  border-radius: 6px;
  margin-bottom: 16px;
}
.query-form .el-form-item {
  margin-right: 20px;
}
.no-data {
  text-align: center;
  color: #909399;
  margin-top: 16px;
}
</style>
